//
//  PowerCircleView.swift
//  STest
//
//  Created by wang tiao on 2025/9/5.
//

import UIKit
import SnapKit

struct PowerSegment {
    let value: CGFloat
    let color: UIColor
    let title: String
}

class PowerCircleView: UIView {
    
    var segments: [PowerSegment] = [] {
        didSet { setNeedsDisplay(); setupLegend() }
    }
    
    private let centerLabel = UILabel()
    private let legendStack = UIStackView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        setupCenterLabel()
        setupLegendStack()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupCenterLabel() {
        centerLabel.numberOfLines = 0
        centerLabel.textAlignment = .center
        centerLabel.font = UIFont.boldSystemFont(ofSize: 22)
        centerLabel.textColor = .white
        addSubview(centerLabel)
        
        centerLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    private func setupLegendStack() {
        legendStack.axis = .vertical
        legendStack.spacing = 8
        legendStack.alignment = .leading
        addSubview(legendStack)
        
        legendStack.backgroundColor = .red
        
        legendStack.snp.makeConstraints { make in
            make.leading.equalTo(self.snp.trailing).offset(20)
            make.centerY.equalToSuperview()
        }
    }
    
    private func setupLegend() {
        legendStack.arrangedSubviews.forEach { $0.removeFromSuperview() }
        for segment in segments {
            let item = legendItem(color: segment.color, title: segment.title)
            legendStack.addArrangedSubview(item)
        }
    }
    
    private func legendItem(color: UIColor, title: String) -> UIView {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.spacing = 6
        stack.alignment = .center // 🔥 关键：让子视图居中，而不是被拉伸
        
        let dot = UIView()
        dot.backgroundColor = color
        dot.layer.cornerRadius = 5
        
        dot.snp.makeConstraints { make in
            make.width.height.equalTo(10)
        }
        
        let label = UILabel()
        label.text = title
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = color
        label.numberOfLines = 0
        label.setContentCompressionResistancePriority(.required, for: .vertical)
        
        stack.addArrangedSubview(dot)
        stack.addArrangedSubview(label)
        
        stack.snp.makeConstraints { make in
            make.height.greaterThanOrEqualTo(20) // 每行至少20
        }
        
        return stack
    }
    override func draw(_ rect: CGRect) {
        guard !segments.isEmpty else { return }
        let ctx = UIGraphicsGetCurrentContext()
        let lineWidth: CGFloat = 12
        let radius = min(rect.width, rect.height) / 2 - lineWidth / 2
        
        let gapAngle: CGFloat = .pi / 180 * 2 // 每段间隔2度，可调
        
        var startAngle: CGFloat = -.pi / 2
        let total = segments.reduce(0) { $0 + $1.value }
        
        for segment in segments {
            ctx?.setStrokeColor(segment.color.cgColor)
            ctx?.setLineWidth(lineWidth)
            ctx?.setLineCap(.butt) // 直角端点
            
            let angle = (segment.value / total) * 2 * .pi
            let endAngle = startAngle + angle - gapAngle
            
            ctx?.addArc(center: CGPoint(x: rect.midX, y: rect.midY),
                        radius: radius,
                        startAngle: startAngle + gapAngle / 2,
                        endAngle: endAngle,
                        clockwise: false)
            ctx?.strokePath()
            startAngle += angle
        }
    }
    
    func setCenterText(top: String, value: String, unit: String) {
        let text = NSMutableAttributedString()
        let topAttr = NSAttributedString(string: "\(top)\n", attributes: [
            .font: UIFont.systemFont(ofSize: 16),
            .foregroundColor: UIColor.gray
        ])
        text.append(topAttr)
        let valueAttr = NSAttributedString(string: "\(value)\n", attributes: [
            .font: UIFont.boldSystemFont(ofSize: 28),
            .foregroundColor: UIColor.white
        ])
        text.append(valueAttr)
        let unitAttr = NSAttributedString(string: unit, attributes: [
            .font: UIFont.systemFont(ofSize: 16),
            .foregroundColor: UIColor.gray
        ])
        text.append(unitAttr)
        
        centerLabel.attributedText = text
    }
}
